package cn.cuilan.test.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 重入锁实现
 *
 * @author zhangyan
 * @since 2023/3/10
 */
public class ReentrantLockPrint {

    private int num;
    private static final Lock lock = new ReentrantLock();

    public void print(int targetNum, String context) {
        for (int i = 0; i < 3; ) {
            // 先获得锁
            lock.lock();
            if (num % 4 == targetNum) {
                System.out.println(Thread.currentThread().getName() + ": " + context);
                num++;
                i++;
            }
            // 释放锁
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockPrint rlp = new ReentrantLockPrint();

        new Thread(() -> rlp.print(0, "A"), "Thread-a").start();
        new Thread(() -> rlp.print(1, "B"), "Thread-b").start();
        new Thread(() -> rlp.print(2, "C"), "Thread-c").start();
        new Thread(() -> rlp.print(3, "D"), "Thread-d").start();
    }
}
